import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';

export default defineConfig(({ mode }) => {
  // 加载环境变量
  const env = loadEnv(mode, process.cwd(), '');
  
  // 基础配置
  const baseConfig = {
    plugins: [vue()],
    server: {
      port: 5174,
      open: true,
      proxy: {
        '/api': {
          target: 'http://localhost:8081',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      }
    },
    // 构建配置
    build: {
      outDir: 'dist',
      assetsDir: 'assets',
      sourcemap: mode === 'development',
      minify: mode === 'production' ? 'terser' : false,
      terserOptions: mode === 'production' ? {
        compress: {
          drop_console: true,
          drop_debugger: true
        }
      } : {}
    },
    // 环境变量
    define: {
      __APP_ENV__: JSON.stringify(env.APP_ENV || mode)
    }
  };

  // 生产环境特定配置
  if (mode === 'production') {
    return {
      ...baseConfig,
      base: '/', // 生产环境的基础路径
      build: {
        ...baseConfig.build,
        rollupOptions: {
          output: {
            chunkFileNames: 'assets/js/[name]-[hash].js',
            entryFileNames: 'assets/js/[name]-[hash].js',
            assetFileNames: 'assets/[ext]/[name]-[hash].[ext]'
          }
        }
      }
    };
  }

  // 测试环境特定配置
  if (mode === 'test') {
    return {
      ...baseConfig,
      base: '/test/', // 测试环境的基础路径
      server: {
        ...baseConfig.server,
        port: 5175
      },
      build: {
        ...baseConfig.build,
        sourcemap: true
      }
    };
  }

  // 开发环境配置
  return baseConfig;
});